<template>
  <div>
    <headerXX :name="title"></headerXX>
    <van-search
      v-model="XXyz.bookName"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @clear="onCancel"
      shape="round"
      style="padding-bottom: 0"
    ></van-search>
    <van-tabs
      color="rgb(2, 117, 113)"
      v-model:active="active"
      @click="onClickTab"
    >
      <van-tab title="待归还"> </van-tab>
      <van-tab title="历史借还"> </van-tab>
    </van-tabs>
    <van-pull-refresh
      class="pull-refresh_Search"
      v-model="refreshing"
      @refresh="onRefresh"
    >
      <van-empty
        v-if="list.length == 0 && !error"
        image="search"
        description="未找到数据"
      />
      <van-empty v-if="error" image="error" description="网络错误" />
      <van-list
        :immediate-check="false"
        v-model:loading="loading"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- 列表内容 -->
        <div class="ulbox" v-if="list.length > 0">
          <div class="ul" v-for="(item, index) in list" :key="index">
            <div class="li">
              <div class="li_left">
                <van-image
                  class="img"
                  radius="4"
                  width="90"
                  height="90"
                  :src="item.bookImage"
                  mode="widthFix"
                >
                </van-image>
              </div>
              <div class="li_right">
                <div class="title" style="font-weight: 600">
                  {{ item.bookName }}
                </div>
                <div class="text WZ_size_10">
                  {{ item.bookDescription }}
                </div>

                <div
                  style="
                    color: rgb(53, 53, 53);
                    display: flex;
                    align-items: center;
                  "
                >
                  <div class="li_rightDD">
                    <div class="ZZtext">作者：{{ item.bookAuthor }}</div>
                    <div
                      style="background: #c8c9cc"
                      class="li_rightXX"
                      v-if="item.orderStatus == 2"
                    >
                      已借出
                    </div>
                    <div
                      style="color: #ff9900; border-color: #ff9900"
                      class="li_rightXX"
                      v-else-if="item.orderStatus == 0"
                    >
                      待归还
                    </div>
                    <div
                      @click.stop="JYchildTap(item)"
                      class="li_rightXX"
                      v-else
                    >
                      借 阅
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- <div v-for="(item, index) in list" :key="index" class="item">
        
        {{ item.districtName }}
      </div> -->

        <!-- 自定义错误提示（可选增强样式） -->
        <template #error>
          <div class="error-tip" @click="retryLoad">
            <van-icon name="warning" />
            <span>加载失败，点击重试</span>
          </div>
        </template>
      </van-list>
    </van-pull-refresh>
    <ReL
      @calendar="calendar"
      @closeCalendar="closeCalendar"
      :dateshow="dateshow"
    />
  </div>
</template>

<script>
import { getmoreRoute } from "../../common/moreRouteList";
import {
  getBookHistoryList,
  completeServiceOrder,
} from "@/api/realAssets/icsharedstation/GXSW/index.js";
import { getAccessToken } from "../../common/YYSLxx.js";
import headerXX from "../../components/title.vue";
import { selectUser } from "@/api/realAssets/icsharedstation/home";
import { getandroidCode } from "../../common/auth";
import moment from "moment";
import ReL from "../../components/ReL.vue";
import { Toast, Dialog } from "vant";
export default {
  components: { headerXX, ReL },
  data() {
    return {
      active: 0,
      title: "我的借阅",
      siteData: JSON.parse(localStorage.getItem("siteData")),
      XXyz: {
        siteId: 0,
        bookName: "",
        pageNumber: 1,
        pageSize: 10,
        orderStatus: "0",
        orderMobile: "",
        postId: "",
      },
      finished: false,
      error: false,
      loading: false,
      refreshing: false,
      list: [],
      dateshow: false,
      objXX: {},
      dateXX: "",
    };
  },
  created() {
    //获取该用户手机号
    selectUser({
      ishid: getandroidCode(), //拿到编码
    }).then((resXX) => {
      this.XXyz.orderMobile = resXX.data.mobile; //手机号
      this.XXyz.postId = JSON.parse(localStorage.getItem("siteData")).postId;
      this.onLoad();
    });
  },
  mounted() {},
  methods: {
    // 下拉刷新
    onRefresh() {
      //   list.value = [];
      this.XXyz.pageNumber = 1;
      this.XXyz.pageSize = 10;
      this.finished = false;
      this.error = false;
      this.loading = true;
      this.refreshing = true;
      this.onLoad();
    },

    // 点击重试
    retryLoad() {
      this.error = false;
      this.loading = true;
      this.onLoad();
    },
    // 加载数据
    onLoad() {
      this.loading = true;
      if (this.error) return; // 如果当前是错误状态，不自动触发加载
      if (this.refreshing) {
        this.list = [];
      }
      this.XXyz.siteId = this.siteData.id;
      console.log(this.XXyz.orderStatus);
      getBookHistoryList(this.XXyz).then((res) => {
        if (res.resultMessage != "SUCCESS") {
          this.list = [];
          this.error = true; // 显示错误提示
          // loading.value = false;
        } else if (res.data.length == 0) {
          this.list = [];
          this.finished = true;
        } else {
          this.list = [...this.list, ...res.data];
          // list.value = res.data;
        }
        this.loading = false;
        // 判断是否已加载完所有数据
        if (this.list.length == res.pageNum) {
          this.finished = true;
        } else {
          this.XXyz.pageNumber++;
        }
        this.refreshing = false;
      });
    },
    //清空搜索
    onCancel() {
      // console.log(XXyz.value.districtName);
      // XXyz.value.districtName = "";
      this.onRefresh();
    },
    onClickTab(val) {
      if (val == 0) {
        this.XXyz.orderStatus = "0";
      } else if (val == 1) {
        this.XXyz.orderStatus = "";
      }
      this.onRefresh();
    },
    //按键触发
    onSearch() {
      this.onRefresh();
    },
    childTap(val) {
      let obj = {
        serviceType: "共享书屋",
        bookList: [
          {
            id: val.id,
            requestQty: 1,
          },
        ],
        id: val.orderId,
        siteId: val.siteId,
        postId: this.XXyz.postId,
        userId: val.orderMobile,
      };
      completeServiceOrder(obj).then((res) => {
        if (res.data == "SUCCESS") {
          Toast.success("归还成功");
          this.onRefresh();
        } else {
          Toast.fail("归还失败");
        }
      });
    },
    JYchildTap(val) {
      this.dateshow = true;
      this.objXX = val;
    },
    closeCalendar(val) {
      this.dateshow = val;
    },
    calendar(e) {
      this.dateshow = false;
      this.dateXX = e;
      const currentTimeStamp = moment().unix();
      const min = BigInt("1" + "0".repeat(18)); // 10^18
      const max = BigInt("1" + "0".repeat(19)); // 10^19
      const randomNum =
        min + BigInt(Math.floor(Math.random() * Number(max - min)));
      let itemXX = {
        SBBT: "共享书屋",
        orderNumber: currentTimeStamp + randomNum.toString(), //预约编号
        siteId: this.siteData.id,
        orderProject: this.title, //预约项目
        goodInfo: [
          {
            id: this.objXX.goodId,
            requestQty: 1,
            siteId: this.siteData.id,
          },
        ],
        orderProjectType: "0", //0:   1:  (区分健康自测类型与其他类型)
        orderCreationTime: moment().format("YYYY-MM-DD"), //下单时间
        estimateArrivalTime: this.dateXX, //预估时间
        estimateArrivalTimeTitle: "归还日期",
        estimateSumPrice: "", //预估费用
        orderSubType: "", //预约类型
        serviceDescription: "", //服务介绍
        orderLocation: "", //预约地址(非空展示)
        serviceTip: "", //温馨提示(非空展示)
        goodSumPrice: "", //总价
        serviceTitleList: ["书名", "", "数量", ""], //服务标题
        goodList: [
          {
            goodId: this.objXX.goodId,
            goodName: this.objXX.goodName,
            servicePrice: "",
            serviceQty: "1",
            goodCountPrice: "",
            goodQty: "1",
            serviceProjectName: "",
            serviceProjectNameTitle: "",
            remark: "",
            remarkTitle: "",
            serviceMessage: "",
            serviceMessageTitle: "",
          },
        ],
      };
      //console.log(itemXX);
      getAccessToken(itemXX, "共享书屋");
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../static/css/index.less";
@import "../../static/css/GYcSS.less";
.pull-refresh_Search {
  height: calc(
    var(--real-vh, 1vh) * 100 - 135px - env(safe-area-inset-bottom) -
      env(safe-area-inset-top)
  );
}

.SMbox {
  position: relative;

  .SM {
    position: absolute;
    top: 80%;
    left: 50%;
    transform: translate(-50%, 0%);
  }
}

.ulbox {
  .ul {
    padding-top: 0px !important;
  }
}

.CX {
  display: flex;
  justify-content: space-between;
}

.title {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.text {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.li_rightDD {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin-top: 10px;
  .li_rightXX {
    border-radius: 5px;
    font-size: 12px;
    width: 50px;
    height: 25px;
    line-height: 25px;
    background: rgb(2, 117, 113);
    color: #fff;
    text-align: center;
  }
}

.CX {
  display: flex;
  justify-content: space-between;
}

.ulbox {
  .ul {
    padding-top: 0px !important;
  }
}

.CX {
  display: flex;
  justify-content: space-between;
}

.title {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
.text {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.ZZtext {
  width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.li_rightDD {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .li_rightXX {
    border-radius: 15px;
    font-size: 12px;
    width: 50px;
    height: 25px;
    line-height: 25px;
    border: rgb(54, 194, 168) 1px solid;
    background: #fff;
    color: rgb(54, 194, 168);
    text-align: center;
  }
}
</style>